import { useEffect } from 'react'

import { createRoleApi, queryRoleTreeApi, updateRoleApi } from '@/api/sys/roleManage'
import AekForm from '@/components/AekForm'
import AekModal, { PromiseThen } from '@/components/AekModal'
import EnumManager from '@/utils/enum'
import { requestWithTry } from '@/utils/request'

export const RoleTypeEnum = new EnumManager({
  CLASSIFICATION_ROLE: { value: 1, label: '分类角色' },
  LEVEL_ROLE: { value: 2, label: '级别角色' },
})

const EditModal = ({ row = {} }) => {
  const [form] = AekForm.useForm()
  const { roleId } = row

  useEffect(() => {
    if (!roleId) return
    form.setFieldsValue({
      ...row,
    })
  }, [roleId])

  /** @type {import("@/components/AekForm").FormDataProps[]} */
  const formData = [
    {
      exclude: roleId,
      field: 'parentRoleId',
      label: '上级角色',
      component: {
        name: 'AekTreeSelect',
        props: {
          api: queryRoleTreeApi,
          fieldNames: {
            value: 'roleId',
            label: 'roleName',
          },
          contentRender: data => {
            data.forEach(item => delete item.children)
            return data
          },
        },
      },
    },
    {
      field: 'roleName',
      label: '角色名称',
      formItemProps: {
        rules: [{ required: true }],
      },
      component: {
        name: 'Input',
        props: {
          maxLength: 20,
          placeholder: '10个字以内',
        },
      },
    },
  ]

  const onOk = async () => {
    const values = await form.validateFields()
    const params = {
      roleId,
      ...values,
      roleType: RoleTypeEnum[values.parentRoleId ? 'LEVEL_ROLE' : 'CLASSIFICATION_ROLE'],
    }
    await requestWithTry(roleId ? updateRoleApi : createRoleApi, params)
  }
  return (
    <AekModal title={roleId ? '编辑' : '新增'} width={500} onOk={onOk}>
      <AekForm form={form} formData={formData} />
    </AekModal>
  )
}

EditModal.PromiseThen = PromiseThen

export default EditModal
